<template>
    <div class="dashboard-container">
        <!-- 顶部数据卡片 -->
        <el-row :gutter="20" class="mb-20">
            <el-col :span="6" v-for="(item, index) in statCards" :key="index">
                <el-card class="stat-card" shadow="hover">
                    <div class="stat-content">
                        <div class="stat-icon" :class="item.type">
                            <el-icon><component :is="item.icon" /></el-icon>
                        </div>
                        <div class="stat-info">
                            <div class="stat-title">{{ item.title }}</div>
                            <div class="stat-value">{{ item.value }}
                                <span class="unit">{{ item.unit }}</span>
                            </div>
                            <div class="stat-compare">
                                较昨日
                                <span :class="item.trend >= 0 ? 'up' : 'down'">
                                    {{ Math.abs(item.trend) }}%
                                    <el-icon><component :is="item.trend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                                </span>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="mb-20">
            <!-- 订单趋势图 -->
            <el-col :span="15">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span class="title">订单趋势</span>
                            <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                                <el-radio-button value="week">近7天</el-radio-button>
                                <el-radio-button value="month">近30天</el-radio-button>
                            </el-radio-group>
                        </div>
                    </template>
                    <ECharts :options="orderTrendOptions" class="trend-chart" />
                </el-card>
            </el-col>
            <!-- 服务类型占比 -->
            <el-col :span="9">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span class="title">服务类型占比</span>
                        </div>
                    </template>
                    <ECharts :options="serviceTypeOptions" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 底部图表 -->
        <el-row :gutter="20">
            <!-- 客户类型分布 -->
            <el-col :span="12">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span class="title">客户类型分布</span>
                        </div>
                    </template>
                    <ECharts :options="platformOptions" />
                </el-card>
            </el-col>
            <!-- 收入统计 -->
            <el-col :span="12">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span class="title">收入统计</span>
                            <div class="date-picker">
                                <el-date-picker
                                    v-model="incomeDateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    value-format="YYYY-MM-DD"
                                    :picker-options="pickerOptions"
                                />
                                <el-button type="primary" @click="handleIncomeQuery" class="query-btn">查询</el-button>
                            </div>
                        </div>
                    </template>
                    <ECharts :options="incomeOptions" />
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import ECharts from '@/components/ECharts.vue'
import type { ComposeOption } from 'echarts/core'
import type {
    TitleComponentOption,
    TooltipComponentOption,
    GridComponentOption,
    LegendComponentOption
} from 'echarts/components'
import type {
    LineSeriesOption,
    BarSeriesOption,
    PieSeriesOption
} from 'echarts/charts'
import type { EChartsOption } from 'echarts'
import {
    getOrderTrendData,
    getServiceTypeStatistics,
    getCustomerTypeStatistics,
    getIncomeStatistics,
    getTodayStatistics
} from '@/api/statistics'
import { useLocale } from 'element-plus'

// 类型定义
type ECOption = ComposeOption<
    | TitleComponentOption
    | TooltipComponentOption
    | GridComponentOption
    | LegendComponentOption
    | LineSeriesOption
    | BarSeriesOption
    | PieSeriesOption
>

// 状态定义
const timeRange = ref('week')
const incomeDateRange = ref<[string, string]>(['', ''])

// 设置中文语言
const locale = useLocale()
locale.locale.value = 'zh-cn' as any

// 日期选择器配置
const pickerOptions = {
    disabledDate(time: Date) {
        const now = new Date()
        const threeMonthsAgo = new Date()
        threeMonthsAgo.setMonth(now.getMonth() - 3)
        return time.getTime() > now.getTime() || time.getTime() < threeMonthsAgo.getTime()
    },
    shortcuts: [
        {
            text: '最近一周',
            value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
            }
        },
        {
            text: '最近一个月',
            value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
            }
        },
        {
            text: '最近三个月',
            value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
            }
        }
    ]
}

// 顶部统计卡片数据
const statCards = ref([
    {
        title: '今日订单',
        value: '0',
        unit: '单',
        icon: 'Document',
        type: 'primary',
        trend: 0
    },
    {
        title: '今日成交额',
        value: '0',
        unit: '元',
        icon: 'Money',
        type: 'success',
        trend: 0
    },
    {
        title: '平均订单金额',
        value: '0',
        unit: '元',
        icon: 'Wallet',
        type: 'warning',
        trend: 0
    },
    {
        title: '订单转化率',
        value: '0',
        unit: '%',
        icon: 'TrendCharts',
        type: 'info',
        trend: 0
    }
])

// 获取今日统计数据
const fetchTodayStatistics = async () => {
    try {
        const data = await getTodayStatistics()
        statCards.value = [
            {
                title: '今日订单',
                value: data.orderCount.toString(),
                unit: '单',
                icon: 'Document',
                type: 'primary',
                trend: data.orderCountTrend
            },
            {
                title: '今日成交额',
                value: data.totalAmount.toFixed(2),
                unit: '元',
                icon: 'Money',
                type: 'success',
                trend: data.totalAmountTrend
            },
            {
                title: '平均订单金额',
                value: data.averageOrderAmount.toFixed(2),
                unit: '元',
                icon: 'Wallet',
                type: 'warning',
                trend: data.averageOrderAmountTrend
            },
            {
                title: '订单转化率',
                value: data.conversionRate.toFixed(2),
                unit: '%',
                icon: 'TrendCharts',
                type: 'info',
                trend: data.conversionRateTrend
            }
        ]
    } catch (error) {
        ElMessage.error('获取今日统计数据失败')
    }
}

// 图表配置
const orderTrendOptions = ref<any>({
    tooltip: { trigger: 'axis' },
    legend: {
        data: ['订单数量', '成交金额'],
        padding: [5, 10]
    },
    grid: {
        left: '12%',
        right: '8%',
        bottom: '8%',
        top: '10%',
        containLabel: true
    },
    xAxis: {
        type: 'category' as const,
        boundaryGap: false,
        data: [] as string[],
        axisLabel: { margin: 12, fontSize: 12 }
    },
    yAxis: [
        {
            type: 'value' as const,
            name: '订单数量',
            position: 'left',
            nameTextStyle: { padding: [0, 0, 0, 30] }
        },
        {
            type: 'value' as const,
            name: '成交金额',
            position: 'right',
            axisLabel: { formatter: '{value} 元' },
            nameTextStyle: { padding: [0, 30, 0, 0] }
        }
    ],
    series: [
        {
            name: '订单数量',
            type: 'line' as const,
            smooth: true,
            data: [] as number[],
            symbolSize: 6,
            lineStyle: { width: 2 }
        },
        {
            name: '成交金额',
            type: 'line' as const,
            smooth: true,
            yAxisIndex: 1,
            data: [] as number[],
            symbolSize: 6,
            lineStyle: { width: 2 }
        }
    ]
})

const serviceTypeOptions = ref<any>({
    tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [
        {
            name: '服务类型',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['55%', '45%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: { show: false, position: 'center' },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '14',
                    fontWeight: 'bold'
                }
            },
            labelLine: { show: false },
            data: []
        }
    ]
})

const platformOptions = ref<any>({
    tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
    },
    legend: { data: ['订单数量', '订单金额'] },
    grid: {
        left: '4%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: [{ type: 'category', data: [] }],
    yAxis: [
        {
            type: 'value',
            name: '订单数量',
            position: 'left'
        },
        {
            type: 'value',
            name: '订单金额',
            position: 'right',
            axisLabel: { formatter: '{value} 元' }
        }
    ],
    series: [
        { name: '订单数量', type: 'bar', data: [] },
        { name: '订单金额', type: 'bar', yAxisIndex: 1, data: [] }
    ]
})

const incomeOptions = ref<any>({
    tooltip: { trigger: 'axis' },
    legend: { data: ['总收入', '平台佣金', '净收入'] },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []
    },
    yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value} 元' }
    },
    series: [
        {
            name: '总收入',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: { focus: 'series' },
            data: []
        },
        {
            name: '平台佣金',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: { focus: 'series' },
            data: []
        },
        {
            name: '净收入',
            type: 'line',
            stack: 'Total',
            areaStyle: {},
            emphasis: { focus: 'series' },
            data: []
        }
    ]
})

// 数据处理函数
const handleTimeRangeChange = async (value: string | number | boolean | undefined) => {
    if (typeof value !== 'string') return
    
    try {
        const data = await getOrderTrendData(value as 'week' | 'month')
        orderTrendOptions.value = {
            ...orderTrendOptions.value,
            xAxis: {
                ...orderTrendOptions.value.xAxis,
                data: data.dates
            },
            series: [
                {
                    ...orderTrendOptions.value.series[0],
                    data: data.orderCounts
                },
                {
                    ...orderTrendOptions.value.series[1],
                    data: data.orderAmounts
                }
            ]
        }
    } catch (error) {
        ElMessage.error('获取订单趋势数据失败')
    }
}

const handleServiceTypeStatistics = async () => {
    try {
        const data = await getServiceTypeStatistics()
        serviceTypeOptions.value = {
            ...serviceTypeOptions.value,
            series: [{
                ...serviceTypeOptions.value.series[0],
                data: data.map((item: any) => ({
                    value: item.count,
                    name: item.serviceType,
                    percentage: item.percentage.toFixed(2)
                }))
            }]
        }
    } catch (error) {
        ElMessage.error('获取服务类型统计数据失败')
    }
}

const handleCustomerTypeStatistics = async () => {
    try {
        const data = await getCustomerTypeStatistics()
        platformOptions.value = {
            ...platformOptions.value,
            xAxis: [{
                ...platformOptions.value.xAxis[0],
                data: data.map((item: any) => item.customerType)
            }],
            series: [
                {
                    ...platformOptions.value.series[0],
                    data: data.map((item: any) => item.orderCount)
                },
                {
                    ...platformOptions.value.series[1],
                    data: data.map((item: any) => item.totalAmount)
                }
            ]
        }
    } catch (error) {
        ElMessage.error('获取客户类型统计数据失败')
    }
}

const handleIncomeQuery = async () => {
    if (!incomeDateRange.value || incomeDateRange.value.length !== 2) {
        ElMessage.warning('请选择日期范围')
        return
    }
    
    try {
        const [startDate, endDate] = [...incomeDateRange.value]
        const data = await getIncomeStatistics(startDate, endDate)
        
        incomeOptions.value = {
            ...incomeOptions.value,
            xAxis: {
                ...incomeOptions.value.xAxis,
                data: data.months
            },
            series: [
                {
                    ...incomeOptions.value.series[0],
                    data: data.totalIncomes
                },
                {
                    ...incomeOptions.value.series[1],
                    data: data.platformCommissions
                },
                {
                    ...incomeOptions.value.series[2],
                    data: data.netIncomes
                }
            ]
        }
    } catch (error) {
        ElMessage.error('获取收入统计数据失败')
    }
}

// 初始化数据
onMounted(() => {
    handleTimeRangeChange('week')
    handleServiceTypeStatistics()
    handleCustomerTypeStatistics()
    fetchTodayStatistics()
    
    // 设置默认日期范围为最近三个月
    const endDate = new Date()
    const startDate = new Date()
    startDate.setMonth(startDate.getMonth() - 3)
    incomeDateRange.value = [
        startDate.toISOString().split('T')[0],
        endDate.toISOString().split('T')[0]
    ]
    handleIncomeQuery()
})
</script>

<style scoped>
.dashboard-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: calc(100vh - 60px);
}

.mb-20 {
    margin-bottom: 20px;
}

/* 统计卡片样式 */
.stat-card {
    background: #fff;
    border: none;
}

.stat-content {
    display: flex;
    align-items: center;
    padding: 10px;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
}

.stat-icon.primary {
    background: #ecf5ff;
    color: #409EFF;
}

.stat-icon.success {
    background: #f0f9eb;
    color: #67C23A;
}

.stat-icon.warning {
    background: #fdf6ec;
    color: #E6A23C;
}

.stat-icon.info {
    background: #f4f4f5;
    color: #909399;
}

.stat-icon :deep(.el-icon) {
    font-size: 24px;
}

.stat-info {
    flex: 1;
}

.stat-title {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    line-height: 1;
    margin-bottom: 8px;
}

.stat-value .unit {
    font-size: 14px;
    margin-left: 4px;
    font-weight: normal;
    color: #909399;
}

.stat-compare {
    font-size: 12px;
    color: #909399;
}

.stat-compare .up {
    color: #67C23A;
}

.stat-compare .down {
    color: #F56C6C;
}

/* 图表卡片样式 */
.chart-card {
    background: #fff;
    border: none;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chart-header .title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
}

.date-picker {
    margin-left: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.query-btn {
    margin-left: 8px;
}

:deep(.el-card__header) {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
    padding: 20px;
}
</style>